package com.baocai.tools_redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.UUID;

/**
 * @author ：minyang
 * @date ：Created in 2019/7/26 7:31
 * 限流工具类
 */
public class LimitingUtil {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 滑动窗口限流
     *
     * @return
     */
    public Boolean limitFlow() {
        Long currentTime = new Date().getTime();
        int intervalTime = 5000;
        System.out.println(currentTime);
        if (redisTemplate.hasKey("limit")) {
            Integer count = redisTemplate.opsForZSet().rangeByScore("limit", currentTime - intervalTime, currentTime).size();        // intervalTime是限流的时间
            System.out.println(count);
            if (count != null && count > 5) {
                return false; //每分钟最多只能访问5次
            }
        }
        redisTemplate.opsForZSet().add("limit", UUID.randomUUID().toString(), currentTime);
        return true;
    }

    /**
     * 令牌桶限流
     *
     * @param id
     * @return
     */
    public Boolean limitFlow2(Long id) {
        Object result = redisTemplate.opsForList().leftPop("limit_list");
        if (result == null) {
            return false;//当前令牌桶中无令牌
        }
        return true;
    }

    /**
     * 定时往令牌桶加令牌
     */
    //@Scheduled(fixedDelay = 10_000,initialDelay = 0)
    public void setIntervalTimeTask() {
        redisTemplate.opsForList().rightPush("limit_list", UUID.randomUUID().toString());
    }

}
